// 云函数入口文件
const cloud = require('wx-server-sdk')
const jwt = require('jsonwebtoken')
cloud.init({ env: 's-web-devin-3gvwv5vda1185f99' }) // 使用当前云环境

// 数据库操作句柄
const db = cloud.database()
// 登陆函数
const useLogin = async ({ username, password }) => {

  const data = await db.collection('users').where({ username, password }).get()
  if (data.data.length) {
    const token = jwt.sign({ ...data.data[0] }, '2006A', { expiresIn: '1h' })
    return {
      code: 0,
      msg: 'sussess',
      data: { token }
    }
  } else {
    return {
      code: -1,
      msg: '当前用户不存在'
    }
  }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { username, password } = event
  const response = await useLogin({ username, password })
  return {
    ...response
  }
}